package com.cndcare.msc.netty.controller.api;

import com.cndcare.msc.cloud.base.result.RestResult;
import com.cndcare.msc.cloud.base.result.RestResultUtil;
import com.cndcare.msc.config.MyWebSocket;
import com.cndcare.msc.netty.bean.PcBean;
import com.cndcare.msc.netty.dao.jpa.PcBeanJpa;
import com.cndcare.msc.service.NettyService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/pc")
public class PcApiController {

    @Autowired
    private PcBeanJpa pcBeanJpa;
    @Autowired
    private NettyService nettyService;
    @Autowired
    private MyWebSocket myWebSocket;
    @Autowired
    private ObjectMapper objectMapper;

    @GetMapping("/pcInfo")
    public PcBean pcInfo(
            @RequestParam("mac") String mac,
            @RequestParam("ip") String ip
    ) {
        PcBean pcBean = pcBeanJpa.findByMac(mac);
        if (null == pcBean) {
            pcBean = pcBeanJpa.save(PcBean.builder().mac(mac).ip(ip).build());
        }

        return pcBean;
    }

    @PostMapping("/savePc")
    public PcBean savePc(
            @RequestParam("mac") String mac,
            @RequestParam("address") String address,
            @RequestParam("remark") String remark
    ) {
        PcBean pcBean = pcBeanJpa.findByMac(mac);

        pcBean.setAddress(address);
        pcBean.setRemark(remark);
        pcBean.setUpdateTime(new Date());
        nettyService.dealPcByMac(pcBean);
        pcBeanJpa.saveAndFlush(pcBean);

        myWebSocket.broadcastStatus();

        return pcBean;
    }


}
